<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebRTC Camera Switch</title>
  <style>
    #localVideo {
      width: 100%;
      height: auto;
      border: 1px solid black;
    }

    button {
      margin: 10px;
    }
  </style>
</head>

<body>
  <h1>WebRTC Camera Switch Example</h1>

  <!-- Video element for local stream -->
  <video id="localVideo" autoplay muted></video>

  <!-- Button to switch camera -->
  <button id="switchButton">Switch Camera</button>

  <script>
    let localStream;
    let currentDeviceId = null;

    // 初始化本地摄像头
    function initializeCamera(deviceId = null) {
      // 如果有设备ID，使用该ID来选择摄像头
      const constraints = {
        video: deviceId ? { deviceId: { exact: deviceId } } : true,
        audio: true
      };

      navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
          // 绑定本地视频流
          localStream = stream;
          document.getElementById('localVideo').srcObject = stream;
          // 获取当前摄像头设备ID
          const videoTrack = stream.getVideoTracks()[0];
          const device = videoTrack.getSettings();
          currentDeviceId = device.deviceId;


        })
        .catch(error => {
          console.error('无法访问摄像头或麦克风', error);
        });
    }

    // 切换摄像头
    function switchCamera() {
      if (localStream) {
        // 停止当前的视频轨道
        const videoTrack = localStream.getVideoTracks()[0];
        videoTrack.stop();

        // 获取所有的视频输入设备
        navigator.mediaDevices.enumerateDevices()
          .then(devices => {
            const videoDevices = devices.filter(device => device.kind === 'videoinput');

            // 获取下一个设备ID
            const currentDeviceIndex = videoDevices.findIndex(device => device.deviceId === currentDeviceId);
            const nextDeviceIndex = (currentDeviceIndex + 1) % videoDevices.length;
            const nextDeviceId = videoDevices[nextDeviceIndex].deviceId;

            // 使用新的设备ID重新获取视频流
            initializeCamera(nextDeviceId);
          })
          .catch(error => {
            console.error('获取设备列表失败', error);
          });
      }
    }

    // 初始化第一个可用的摄像头
    initializeCamera();

    // 添加按钮事件
    document.getElementById('switchButton').addEventListener('click', switchCamera);
  </script>
</body>

</html>